package com.yowasa.xiuxian.util;

import com.google.common.collect.Lists;
import org.apache.logging.log4j.util.BiConsumer;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class ContentUtil {
    /**
     * 获取所有用户
     *
     * @param content
     * @return
     */
    public static List<String> getAllUser(String content) {
        Pattern pattern = Pattern.compile("<@!([0-9]*)>");
        Matcher matcher = pattern.matcher(content);
        List<String> users = Lists.newArrayList();
        while (matcher.find()) {
            users.add(matcher.group(1));
        }
        return users;
    }

    /**
     * 提取不包含用户at信息的消息
     *
     * @param content
     * @return
     */
    public static String getNoUserContent(String content) {
        if (StringUtils.isEmpty(content)) {
            return "";
        }
        String msg = content.replaceAll("@汐颜bot", "").trim();
        return msg.split("@")[0];
    }

    /**
     * 获取不含指令传入的参数
     *
     * @param content
     * @param cmd
     * @return
     */
    public static String getParam(String content, String cmd) {
        List<String> allParam = getAllParam(content, cmd);
        if (CollectionUtils.isEmpty(allParam)) {
            return null;
        }
        return allParam.get(0);
    }

    /**
     * 获取不含指令的参数列表
     *
     * @param content
     * @param cmd
     * @return
     */
    public static List<String> getAllParam(String content, String cmd) {
        String msg = getNoUserContent(content);
        msg = msg.replace(cmd, "").trim();
        return Arrays.stream(msg.split(" ")).collect(Collectors.toList());
    }

    /**
     * 构建at信息
     *
     * @param userId
     * @return
     */
    public static String buildAt(String userId) {
        return MessageFormat.format("<@!{0}>", userId);
    }


    public static <T> Consumer<T> getIndex(BiConsumer<T, Integer> consumer) {
        class IndexObject {
            int index;
        }
        IndexObject indexObject = new IndexObject();
        return i -> {
            consumer.accept(i, indexObject.index++);
        };
    }


}
